<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警示提示框 -->
      <el-alert :closable="false" title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <div>选择商品分类：
         <el-cascader
            v-model="cascaderValue"
            :options="goodsCates"
            :props="cascaderProp"
            @change="cascaderHandleChange">
          </el-cascader>
      </div>
      <!-- 动态标签页 -->
      <el-tabs v-model="activeName" @tab-click="tabsHandleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加属性的按钮 -->
          <el-button @click="addParamsDialogVisible=true" :disabled="isDisabled" type="primary" size="mini" >添加属性</el-button>
          <!-- 表格数据 -->
          <el-table border stripe :data="manyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag渲染标签 -->
                <el-tag closable @close="removeTag(scope.row,index)" v-for="(item, index) in scope.row.attr_vals"  :key="index">{{item}}</el-tag>
                <!-- Tag输入框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)" >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button @click="addParamsDialogVisible=true" :disabled="isDisabled" type="primary" size="mini" >添加属性</el-button>
          <!-- 表格数据 -->
          <el-table border stripe :data="onlyTableData">
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" width="200">
               <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
       </el-tabs>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog @close="closeAddParams" :title="addParams" :visible.sync="addParamsDialogVisible" width="50%">
      <el-form ref="addParamsRef" :model="addParamsForm" label-width="80px" :rules="addParamsRules">
        <el-form-item label="属性名称" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sumitAddParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类的对话框 -->
    <el-dialog :title="addParams" :visible.sync="editParamsDialogVisible" width="50%">
      <el-form ref="editParamsRef" :model="editParamsForm" label-width="80px" :rules="addParamsRules">
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sumitEditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类数据
      goodsCates: [],
      // 级联选择器绑定的值
      cascaderValue: [],
      // 级联选择框的配置对象
      cascaderProp: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      // 设置tabs标签页默认选中哪一项
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态参数数据
      onlyTableData: [],
      // 控制添加属性对话框按钮的布尔值
      addParamsDialogVisible: false,
      // 对话框添加属性的form表单值
      addParamsForm: {
        attr_name: ''
      },
      // 添加属性的from表单验证规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ]
      },
      // 编辑属性对话框的布尔值
      editParamsDialogVisible: false,
      // 编辑属性form表单
      editParamsForm: {
        attr_name: ''
      },
      // tag输入框
      inputVisible: false,
      // tag输入框值
      inputValue: ''
    }
  },
  methods: {
    // 获取商品分类列表数据
    async getGoods () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品列表失败！')
      this.goodsCates = res.data
    },
    // 级联选择器change事件
    cascaderHandleChange () {
      this.getParams()
    },
    // tabs标签页change处理函数
    tabsHandleClick () {
      this.getParams()
    },
    // 获取静态或动态参数
    async getParams () {
      if (this.cascaderValue.length !== 3) {
        this.cascaderValue = []
        this.manyTableData = []
        this.onlyTableData = []
        return this.$message('请选择第三级分类')
      }
      const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', {
        params: {
          sel: this.activeName
        }
      })
      // 将返回的attr_vals分割成数组形式
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
        console.log(item)
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else if (this.activeName === 'only') {
        this.onlyTableData = res.data
      }
    },
    // 提交添加属性参数
    sumitAddParams () {
      this.$refs.addParamsRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.post('categories/' + this.cateId + '/attributes', {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加属性失败！')
        this.$message.success('添加属性成功！')
        this.getParams()
        this.addParamsDialogVisible = false
      })
    },
    // 重置添加属性表单form
    closeAddParams () {
      this.$refs.addParamsRef.resetFields()
    },
    // 动态参数编辑按钮
    showEditDialog (row) {
      this.editParamsDialogVisible = true
      this.editParamsForm = { ...row }
    },
    // 编辑按钮提交数据
    sumitEditParams () {
      this.$refs.editParamsRef.validate(async valid => {
        if (!valid) return this.$message.error('请正确输入数据！')
        const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, { attr_name: this.editParamsForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('更新数据失败！')
        this.getParams()
        this.$message.success('更新数据成功！')
        this.editParamsDialogVisible = false
      })
    },
    // 删除
    deleteParams (row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败！')
        this.$message.success('删除成功!')
        this.getParams()
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // tag输入框失去焦点事件
    async handleInputConfirm (row) {
      if (row.inputValue.trim() === '') {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 将添加的tagpush到数组，然后发起请求
      row.attr_vals.push(row.inputValue.trim())
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败！')
      this.$message.success('更新成功！')
      row.inputVisible = false
      row.inputValue = ''
      // console.log(this.inputValue)
    },
    // 点击按钮显示tag输入框
    showInput (row) {
      row.inputVisible = true
      // $nextTick 用来控制dom加载完成
      this.$nextTick(_ => this.$refs.saveTagInput.$refs.input.focus())
    },
    // tag的close事件
    async removeTag (row, index) {
      row.attr_vals.splice(index, 1)
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败！')
      this.$message.success('更新成功！')
    }
  },
  computed: {
    // 判断级联选择器是否选中的3级分类，是否禁用添加属性按钮
    isDisabled () {
      return this.cascaderValue.length !== 3
    },
    // 返回选择的是否为三级分类，如果为true，返回三级的id
    cateId () {
      if (this.cascaderValue.length !== 3) {
        return null
      }
      return this.cascaderValue[2]
    },
    // 计算添加参数对话框按钮的文本值
    addParams () {
      return this.activeName === 'many' ? '添加动态属性' : '添加静态属性'
    }
  },
  created () {
    this.getGoods()
  }
}
</script>

<style lang='less' scoped>
.el-tag{
  margin: 7px;
}
.input-new-tag{
  width: 120px;
}
</style>
